package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.FindPasswordDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.FindPasswordService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.xuecheng.base.execption.XueChengPlusException;

@Service
public class FindPasswordServiceImpl implements FindPasswordService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired(required = false)
    XcUserMapper xcUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 找回密码
     * @param findPasswordDto
     */
    @Override
    public void findPassword(FindPasswordDto findPasswordDto) {
        //校验验证码，不一致则抛出异常
        String checkcode = findPasswordDto.getCheckcode();
        String phoneCode = stringRedisTemplate.opsForValue().get(findPasswordDto.getCellphone());
        String emailCode = stringRedisTemplate.opsForValue().get(findPasswordDto.getEmail());
        if (checkcode==null||(emailCode==null||!emailCode.equals(checkcode)) && (phoneCode==null||!phoneCode.equals(checkcode))) {
            throw new XueChengPlusException("验证码错误！");
        }
        //从redis中删除验证码
        stringRedisTemplate.delete(findPasswordDto.getCellphone());

        //判断两次密码是否一致，不一致则抛出异常
        if (!findPasswordDto.getConfirmpwd().equals(findPasswordDto.getPassword())) {
            throw new XueChengPlusException("两次密码不一样！");
        }
        //根据手机号和邮箱查询用户
        LambdaQueryWrapper<XcUser> wrapper = new LambdaQueryWrapper<>();
        String cellphone = findPasswordDto.getCellphone();
        String email = findPasswordDto.getEmail();
        wrapper.eq(StringUtils.isNotEmpty(cellphone), XcUser::getCellphone, cellphone);
        wrapper.eq(StringUtils.isNotEmpty(email), XcUser::getEmail, email);
        XcUser xcUser = xcUserMapper.selectOne(wrapper);
        //如果找到用户更新为新密码
        if (xcUser != null) {
            //对密码进行加密
            String password = findPasswordDto.getPassword();
            password=passwordEncoder.encode(password);
            //密码
            xcUser.setPassword(password);
            //手机号
            if (cellphone != null) xcUser.setCellphone(cellphone);
            //邮箱
            if (email != null) xcUser.setEmail(email);
            int i = xcUserMapper.updateById(xcUser);
            if (i <= 0) {
                throw new XueChengPlusException("更新密码失败！");
            }
            return;
        }
        throw new XueChengPlusException("该用户未进行注册！");
    }
}
